package api

import (
	"github.com/gin-gonic/gin"
	"jluzh-electric/internal/config"
	source "jluzh-electric/internal/source-api"
	"net/http"
	"sync"
)

func DoGetElectricBalance(c *gin.Context) {
	//get query param

	if len(c.Query("building")) == 0 || len(c.Query("room")) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"message": "please check your query parameters",
		})
		return
	}

	roomId, _ := config.CHNBuildingAndRoomNameToRoomId(c.Query("building"), c.Query("room"))

	//等待请求的数据
	remainingUsage := 0.0 //剩余电量
	balance := 0.0        //余额
	averageUsage := 0.0   //平均使用量
	var concurrentRequestErr error

	/* 开始并发请求数据 */
	{
		var wg sync.WaitGroup
		wg.Add(2)

		//获取电费数据
		go func() {
			remainingUsageReq, balanceReq, balanceErr := source.GetElectricSessionInstance().GetBalance(roomId)

			if balanceErr != nil {
				concurrentRequestErr = balanceErr
			}

			remainingUsage = remainingUsageReq
			balance = balanceReq
			wg.Done()
		}()

		//获取历史用电数据
		go func() {
			averageUsage = source.GetElectricSessionInstance().GetAverageUsage(roomId)
			wg.Done()
		}()
		wg.Wait()
	}
	/* 请求完毕 */

	if concurrentRequestErr != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"message": concurrentRequestErr.Error(),
		})

		return
	}

	//预计剩余天数
	expectedRemain := 0

	if balance > 0 {
		//计算剩余天数前判断是否将发生除以零问题
		if averageUsage != 0 {
			expectedRemain = int(remainingUsage / averageUsage)
		} else {
			expectedRemain = 999
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"remain":         remainingUsage, //剩余电度
		"balance":        balance,        //余额
		"averageUsage":   averageUsage,   //日均使用
		"expectedRemain": expectedRemain, //预计剩余天数
	})
}

func DoGetElectricHistory(c *gin.Context) {
	roomId, _ := config.CHNBuildingAndRoomNameToRoomId(c.Query("building"), c.Query("room"))
	history := source.GetElectricSessionInstance().GetHistory(roomId)
	c.JSON(http.StatusOK, gin.H{
		"data": history,
	})
}

func DoGetRechargeHistory(c *gin.Context) {
	studentId := c.Query("studentId")
	history, err := source.GetElectricSessionInstance().GetRechargeHistory(studentId)

	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"message": err.Error(),
		})

		return
	}

	c.JSON(http.StatusOK, gin.H{
		"data": history,
	})
}
